package org.sauceggplant.item.man.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.sauceggplant.item.man.dao.TypeDao;
import org.sauceggplant.item.man.dto.TypeDto;
import org.sauceggplant.item.man.po.Type;
import org.sauceggplant.item.man.service.TypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class TypeServiceImpl extends AbstractServiceImpl implements TypeService {

    private static final Logger logger = LoggerFactory.getLogger(TypeServiceImpl.class);

    private TypeDao typeDao;

    public TypeServiceImpl() {
        typeDao = new TypeDao();
    }

    @Override
    public List<Type> findAll(TypeDto typeDto) {
        try {
            return typeDao.findAll(typeDto, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(TypeServiceImpl.class.getName(), e);
            return null;
        }
    }

    @Override
    public Integer insert(Type type) {
        try {
            if (StringUtils.isEmpty(type.getName())) {
                throw new NullPointerException("Type.name is not null.");
            }
            if (null == type.getParentId()) {
                type.setParentId(1L);
            }
            if (null == type.getCreateAccount()) {
                type.setCreateAccount(DEFAULT_ACCOUNT);
            }
            if (null == type.getUpdateAccount()) {
                type.setUpdateAccount(DEFAULT_ACCOUNT);
            }
            type.setUuid(uuidService.generateUuid());
            Date now = new Date();
            type.setCreateTime(now);
            type.setUpdateTime(now);
            type.setVersion(1);
            return typeDao.insert(type, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(TypeServiceImpl.class.getName(), e);
            return 0;
        }
    }

    @Override
    public Integer update(Type type) {
        try {
            if (null == type.getUpdateAccount()) {
                type.setUpdateAccount(DEFAULT_ACCOUNT);
            }
            Date now = new Date();
            type.setUpdateTime(now);
            return typeDao.update(type, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(TypeServiceImpl.class.getName(), e);
            return 0;
        }
    }

    @Override
    public Integer delete(Long id) {
        try {
            return typeDao.delete(id, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(TypeServiceImpl.class.getName(), e);
            return 0;
        }
    }
}
